package org.idea.ietty.core.handle;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import io.netty.handler.codec.http.multipart.MemoryAttribute;
import org.idea.ietty.common.constants.IettyConstants;
import org.idea.ietty.common.constants.IettyConstants.*;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.QueryStringDecoder;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.idea.ietty.common.constants.IettyConstants.APPLICATION_JSON;
import static org.idea.ietty.common.constants.IettyConstants.X_WWW_FORM_URLENCODED;

/**
 * 请求处理器
 *
 * @Author idea
 * @Date created in 10:00 下午 2020/5/6
 */
public class ReqHandler {


    /**
     * 获取请求的url地址
     *
     * @param fullHttpRequest
     * @return
     */
    public String getReqUrl(FullHttpRequest fullHttpRequest) {
        String url = fullHttpRequest.uri();
        return (url != null && url != "" && url.contains("?")) ? url.substring(0, url.indexOf("?")) : url;
    }

    /**
     * 获取get方式的请求参数
     *
     * @param fullHttpRequest 请求体
     * @return
     */
    public Map<String, Object> getParameterHandle(FullHttpRequest fullHttpRequest) {
        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(fullHttpRequest.uri());
        Map<String, List<String>> paramMap = queryStringDecoder.parameters();
        if (paramMap != null) {
            Map<String, Object> params = new HashMap<>();
            for (Map.Entry<String, List<String>> entry : paramMap.entrySet()) {
                //这里默认同个键的参数，只接收最后一个
                params.put(entry.getKey(), entry.getValue().get(0));
            }
            return params;
        } else {
            return null;
        }
    }

    /**
     * 获取post请求参数
     *
     * @param fullHttpRequest 请求体
     * @return
     */
    public Map<String, Object> postParameterHandle(FullHttpRequest fullHttpRequest) {
        String contentType = this.getReqHeader(fullHttpRequest);
        Map<String, Object> params = new HashMap<String, Object>();
        if (X_WWW_FORM_URLENCODED.equals(contentType)) {
            HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), fullHttpRequest);
            List<InterfaceHttpData> postData = decoder.getBodyHttpDatas();

            for (InterfaceHttpData data : postData) {
                if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
                    MemoryAttribute attribute = (MemoryAttribute) data;
                    params.put(attribute.getName(), attribute.getValue());
                }
            }
        } else if (APPLICATION_JSON.equals(contentType)) {
            ByteBuf content = fullHttpRequest.content();
            byte[] reqContent = new byte[content.readableBytes()];
            content.readBytes(reqContent);
            String strContent = null;
            try {
                strContent = new String(reqContent, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            params = JSON.parseObject(strContent, Map.class);
            return params;
        }
        return params;
    }


    /**
     * 通过请求判断去请求头的类型
     *
     * @param fullHttpRequest
     * @return
     */
    public String getReqHeader(FullHttpRequest fullHttpRequest) {
        String contentType = fullHttpRequest.headers().get(HttpHeaderNames.CONTENT_TYPE);
        if (contentType != null) {
            return contentType;
        }
        return null;
    }
}
